<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="12">
          <a-form-item label="姓名" v-bind="validateInfos.name">
            <a-input v-model:value="formData.name" placeholder="请输入姓名" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="性别" v-bind="validateInfos.sex">
            <j-dict-select-tag type='radio' v-model:value="formData.sex" dictCode="sex" placeholder="请选择性别" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="工号" v-bind="validateInfos.workNo">
            <a-input v-model:value="formData.workNo" placeholder="请输入工号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="账号" v-bind="validateInfos.userName">
            <a-input v-model:value="formData.userName" placeholder="请输入账号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属部门" v-bind="validateInfos.belongingDepart">
	          <j-select-dept v-model:value="formData.belongingDepart" :multiple="true" checkStrictly :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属岗位" v-bind="validateInfos.workPosition">
	          <j-select-multiple type="list_multi" v-model:value="formData.workPosition" dictCode="sys_position,name,id" placeholder="请选择所属岗位" :disabled="disabled" :triggerChange="false"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="角色" v-bind="validateInfos.roles">
	          <j-search-select v-model:value="formData.roles" dict="sys_role,role_name,id" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号" v-bind="validateInfos.phone">
            <a-input v-model:value="formData.phone" placeholder="请输入手机号" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="民族" v-bind="validateInfos.minzu">
            <a-input v-model:value="formData.minzu" placeholder="请输入民族" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件类型" v-bind="validateInfos.cardType">
            <j-dict-select-tag type='radio' v-model:value="formData.cardType" dictCode="cardType" placeholder="请选择证件类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件号码" v-bind="validateInfos.cardCode">
            <a-input v-model:value="formData.cardCode" placeholder="请输入证件号码" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮编" v-bind="validateInfos.postcode">
            <a-input v-model:value="formData.postcode" placeholder="请输入邮编" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱" v-bind="validateInfos.email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="最高学历" v-bind="validateInfos.educationalBackground">
            <j-dict-select-tag v-model:value="formData.educationalBackground" dictCode="educationalBackground" placeholder="请选择最高学历" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="毕业院校" v-bind="validateInfos.school">
            <a-input v-model:value="formData.school" placeholder="请输入毕业院校" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="户籍所在地" v-bind="validateInfos.domicile">
	          <a-textarea v-model:value="formData.domicile" :rows="4" placeholder="请输入户籍所在地" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="工作经历" v-bind="validateInfos.workExperience">
	          <j-editor v-model:value="formData.workExperience" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="本人照片" v-bind="validateInfos.photograph">
	          <j-image-upload  v-model:value="formData.photograph" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="签名图片" v-bind="validateInfos.signature">
	          <j-image-upload  v-model:value="formData.signature" :disabled="disabled"></j-image-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="人员证书" key="tbPeopleCertificate" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbPeopleCertificateTableRef"
          :loading="tbPeopleCertificateTable.loading"
          :columns="tbPeopleCertificateTable.columns"
          :dataSource="tbPeopleCertificateTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="教育培训" key="tbPeopleEducationTraining" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbPeopleEducationTrainingTableRef"
          :loading="tbPeopleEducationTrainingTable.loading"
          :columns="tbPeopleEducationTrainingTable.columns"
          :dataSource="tbPeopleEducationTrainingTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
      <a-tab-pane tab="奖惩记录" key="tbPeopleRewardsPunishments" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbPeopleRewardsPunishmentsTableRef"
          :loading="tbPeopleRewardsPunishmentsTable.loading"
          :columns="tbPeopleRewardsPunishmentsTable.columns"
          :dataSource="tbPeopleRewardsPunishmentsTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTbPeopleCertificateListByMainId, queryTbPeopleEducationTrainingListByMainId, queryTbPeopleRewardsPunishmentsListByMainId, queryDataById, saveOrUpdate } from '../TbPeople.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tbPeopleCertificateColumns, tbPeopleEducationTrainingColumns, tbPeopleRewardsPunishmentsColumns} from '../TbPeople.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import { Form } from 'ant-design-vue';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TbPeopleForm",
    components:{
      JDictSelectTag,
      JSelectMultiple,
      JSearchSelect,
      JSelectDept,
      JImageUpload,
      JEditor,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tbPeopleCertificateTableRef = ref();
      const tbPeopleCertificateTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbPeopleCertificateColumns,
        dataSource: []
      });
      const tbPeopleEducationTrainingTableRef = ref();
      const tbPeopleEducationTrainingTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbPeopleEducationTrainingColumns,
        dataSource: []
      });
      const tbPeopleRewardsPunishmentsTableRef = ref();
      const tbPeopleRewardsPunishmentsTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbPeopleRewardsPunishmentsColumns,
        dataSource: []
      });
      const activeKey = ref('tbPeopleCertificate');
      const formData = reactive<Record<string, any>>({
        id: '',
        name: '',   
        sex: '',   
        workNo: '',   
        userName: '',   
        belongingDepart: '',   
        workPosition: '',   
        roles: '',   
        phone: '',   
        minzu: '',   
        cardType: '',   
        cardCode: '',   
        postcode: '',   
        email: '',   
        educationalBackground: '',   
        school: '',   
        domicile: '',   
        workExperience: '',   
        photograph: '',   
        signature: '',   
      });

      //表单验证
      const validatorRules = reactive({
        name: [{ required: true, message: '请输入姓名!'},],
        sex: [{ required: true, message: '请输入性别!'},],
        workNo: [{ required: true, message: '请输入工号!'},],
        userName: [{ required: true, message: '请输入账号!'},],
        belongingDepart: [{ required: true, message: '请输入所属部门!'},],
        cardType: [{ required: true, message: '请输入证件类型!'},],
        cardCode: [{ required: true, message: '请输入证件号码!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

      

      function add() {
        resetFields();
        tbPeopleCertificateTable.dataSource = [];
        tbPeopleEducationTrainingTable.dataSource = [];
        tbPeopleRewardsPunishmentsTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tbPeopleCertificateDataList = await queryTbPeopleCertificateListByMainId(row['id']);
        tbPeopleCertificateTable.dataSource = [...tbPeopleCertificateDataList];
        const tbPeopleEducationTrainingDataList = await queryTbPeopleEducationTrainingListByMainId(row['id']);
        tbPeopleEducationTrainingTable.dataSource = [...tbPeopleEducationTrainingDataList];
        const tbPeopleRewardsPunishmentsDataList = await queryTbPeopleRewardsPunishmentsListByMainId(row['id']);
        tbPeopleRewardsPunishmentsTable.dataSource = [...tbPeopleRewardsPunishmentsDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tbPeopleCertificate': tbPeopleCertificateTableRef,
        'tbPeopleEducationTraining': tbPeopleEducationTrainingTableRef,
        'tbPeopleRewardsPunishments': tbPeopleRewardsPunishmentsTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }


      return {
        tbPeopleCertificateTableRef,
        tbPeopleCertificateTable,
        tbPeopleEducationTrainingTableRef,
        tbPeopleEducationTrainingTable,
        tbPeopleRewardsPunishmentsTableRef,
        tbPeopleRewardsPunishmentsTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit
      }
    }
  });
</script>
